<?php namespace Phpcmf\Home;

/**
 * 本文件是框架系统文件，二次开发时不可以修改本文件，可以通过继承类方法来重写此文件
 **/

// 用于前端模块评论显示
class Mform extends \Phpcmf\Common
{
    protected $cid;
    protected $index;
    protected $cname; // 评论别名
    public $module; // 模块信息
    public $fid; // 表单
    public $form; // 表单
    public $comment_model; // 评论模型

    // 上级公共类
    public function __construct() {
        parent::__construct();
        $this->_Extend_Init();
    }

    // 继承类初始化
    protected function _Extend_Init() {
        // 初始化模块

        $this->_module_init(APP_DIR);
        $fid = str_replace(['_comment_verify', '_comment'], '', \Phpcmf\Service::L('Router')->class);
        if (!$this->module['form'][$fid]) {
            $this->_admin_msg(0, dr_lang('模块【%s】表单【%s】不存在', APP_DIR, $fid));
        }
        $cache = \Phpcmf\Service::L('cache')->get('app-comment-'.SITE_ID, 'mform', APP_DIR.'-'.$fid);
        $this->fid = $fid;
        $this->form = $this->module['form'][$fid];
        $this->cname = dr_comment_cname($cache['cname']);
        $this->module['comment'] = $cache;
        if (!$cache) {
            $this->_admin_msg(0, dr_lang('模块【%s】表单【%s】没有安装%s', APP_DIR, $fid, $this->cname));
        } elseif (!$cache['use']) {
            $this->_admin_msg(0, dr_lang('模块【%s】表单【%s】没有启用%s', APP_DIR, $fid, $this->cname));
        }
        $this->comment_model = \Phpcmf\Service::M('mform', 'comment')->_init($this->module, $fid, SITE_ID, $cache);

        // 关联内容数据
        $this->cid = intval(\Phpcmf\Service::L('input')->get('id'));
        $this->index = $this->comment_model->get_row($this->cid);
        if (!$this->index) {
            $this->_msg(0, dr_lang('评论所属模块【%s】表单【%s】内容【id#%s】不存在', APP_DIR, $fid, $this->cid));
        }
        // 格式化输出自定义字段
        $fields = $this->form['field'];
        $fields['inputtime'] = ['fieldtype' => 'Date'];
        $fields['updatetime'] = ['fieldtype' => 'Date'];
        $this->index = \Phpcmf\Service::L('Field')->app($this->module['dirname'])->format_value($fields, $this->index);
        \Phpcmf\Service::V()->module(MOD_DIR);
    }
    
    // 评论列表
    protected function _Index() {

        // 排序模式
        $type = (int)str_replace('#', '', \Phpcmf\Service::L('input')->get('type'));
        $order = '';
        switch ($type) {
            case 1:
                $order = 'inputtime asc';
                break;
            case 2:
                $order = 'support asc';
                break;
            case 3:
                $order = 'avgsort desc';
                break;
            case 4:
                $order = 'image desc';
                break;
            default:
                $_GET['order'] && $order = strtolower(dr_get_order_string($_GET['order'], $order));
                break;
        }
        

        // 判断排序字段是否可用

    if (!dr_in_array(trim(str_replace([' asc', ' desc'], '', $order)), \Phpcmf\Service::L('cache')->get('table-'.SITE_ID, \Phpcmf\Service::M()->dbprefix($this->content_model->mytable.'_comment')))) {
        if (isset($this->module['comment']['order']) && $this->module['comment']['order']) {
            $order = $this->module['comment']['order'];
        } else {
            $order = 'inputtime desc';
        }
    }

        // 获取评论数据
        $comment = $this->comment_model->get_comment_index( $this->cid, $this->index['catid']);
        if (!$comment) {
            exit($this->_msg(0, dr_lang('内容【id#%s】索引数据读取失败',  $this->cid)));
        }

        $page = max(1, (int)\Phpcmf\Service::L('input')->get('page'));
        $total = (int)\Phpcmf\Service::L('input')->get('total');

        if (IS_API_HTTP) {
            $pagesize = (int)$this->module['comment']['pagesize_api'];
        } elseif (\Phpcmf\Service::IS_MOBILE()) {
            $pagesize = (int)$this->module['comment']['pagesize_mobile'];
        } else {
            $pagesize = (int)$this->module['comment']['pagesize'];
        }

        !$pagesize && $pagesize = 10;

        // 查询数据
        list($list, $total) = $this->comment_model->get_comment_result($this->cid, $order, $page, $pagesize, $total, $this->module['comment']['field']);

        // ajax动态无刷新调用
        $js = 'dr_ajax_mform_'.$this->fid.'_comment_'. $this->cid;
		//$jss = 'dr_ajax_mform_'.$this->fid.'_comment_2_'. $this->cid;
        $myfield = \Phpcmf\Service::L('Field')->toform(0, $this->module['comment']['field']);

        
        
        $userweixin=\Phpcmf\Service::M()->db->table('member_oauth')->where('uid', $this->index['uid'])->get()->getRowArray();
        $user=dr_member_info($this->index['uid']);
            //dr_debug('$user', $user);
        if ($user['name']) {
            $this->index['mingcheng'] = $user['name']; 
            $mingcheng = $user['name'];
        } elseif ($userweixin['nickname']) {
            $this->index['mingcheng'] = $userweixin['nickname'];
            $mingcheng = $userweixin['nickname'];
        } else {
            $this->index['mingcheng'] = $user['username'];
            $mingcheng = $user['username'];
        }
        //用户组
        $quanguan = d_guanlizuming($this->index['cid'],$this->index['uid']);
		if($quanguan){
			$this->index['yonghuzu'] = d_guanlizuming($this->index['cid'],$this->index['uid']);
			$yonghuzu = d_guanlizuming($this->index['cid'],$this->index['uid']);
		} else {
			//用户组
			foreach ($user['group'] as $t) {
			    $this->index['yonghuzu'] = $t['group_name'];
			    $yonghuzu = $t['group_name'];
			}
		}
		//用户组
			/*foreach ($user['group'] as $t) {
			    $this->index['yonghuzu'] = $t['group_name'];
			    $yonghuzu = $t['group_name'];
			}*/
        //归属地
        $ip=\Phpcmf\Service::L('ip')->address($this->index['inputip']);
        if ($ip == "未知地区"){
            $this->index['guishudi'] = "中国";
            $guishudi = "中国";
        } else{
            $this->index['guishudi'] = $ip;
            $guishudi = $ip;
        }
        /////////////////////////////
        $this->index['touxiang'] = dr_avatar($this->index['uid']);
        // 下载类型
		if($this->index['xzxz'] ==1) {
		    $fufeixiazai = true;
			// 统一免费
		} elseif ($this->index['xzxz'] ==2) {
			// 会员免费
			$fufeixiazai = \Phpcmf\Service::M()->db->table('1_quan_cart')->where('cid', $this->index['id'])->where('uid', $this->uid)->get()->getRowArray();
			
		} elseif ($this->index['xzxz'] ==3) {
			// 统一付费
			$fufeixiazai = \Phpcmf\Service::M()->db->table('1_quan_xiazai')->where('cid', $this->index['id'])->where('uid', $this->uid)->get()->getRowArray();
			
		} elseif ($this->index['xzxz'] ==4) {
			// 积分
			$fufeixiazai = \Phpcmf\Service::M()->db->table('1_quan_xiazaijifen')->where('cid', $this->index['id'])->where('uid', $this->uid)->get()->getRowArray();
			
		} elseif ($this->index['xzxz'] ==5) {
			// 点赞
			$fufeixiazai = \Phpcmf\Service::M()->db->table('1_quan_form_son_zan')->where('cid', $this->index['id'])->where('uid', $this->uid)->get()->getRowArray();
		} elseif ($this->index['xzxz'] ==6) {
			// 评论
			$fufeixiazai = \Phpcmf\Service::M()->db->table('1_quan_form_son_comment')->where('cid', $this->index['id'])->where('uid', $this->uid)->get()->getRowArray();
		}
		$this->index['fufeixiazai'] = $fufeixiazai || ($this->index['uid'] == $this->uid);
        //圈子信息
        $quantitle = \Phpcmf\Service::M()->db->table('1_quan')->where('id', $this->index['cid'])->get()->getRowArray();
        $this->index['quantitle'] =$quantitle['title'];
        $this->index['quanid'] =$quantitle['id'];
        $this->index['neirong'] =d_huati_app($this->index['neirong']);
		$this->index['jianjie'] = dr_strcut(dr_clearhtml($this->index['neirong']), 40); //
		$this->index['thumb'] = dr_thumb($this->index['thumb'], 240, 240, 0, 'height');
        //付费圈子数据
        $fufei = \Phpcmf\Service::M()->db->table('1_quan_buy')->where('cid', $this->index['cid'])->where('uid', $this->uid)->get()->getRowArray();
        //加入圈子数据
		$cart = \Phpcmf\Service::M()->db->table('1_quan_cart')->where('cid', $this->index['cid'])->where('uid', $this->uid)->get()->getRowArray();
        //判断是否付费
        if($quantitle['price'] > 0){
            if($fufei){
                // 没有到期
                if($fufei['endtime'] > time()){
                    if($cart){
                        // 已经加入
                        $this->index['jiaru'] = 1;
                        $tie = $this->index;
                    } else {
                        // 待加入
                        $this->index['jiaru'] = 3;
                        $this->index['neirong']='待加入圈子';
                        $tie = $this->index;
                    }
                } else {
                    // 续费
                    $this->index['jiaru'] = 4;
                    $this->index['neirong']='已经到期请续费';
                    $tie = $this->index;
                }
                
            } else {
                //付费加入
                $this->index['jiaru'] = 2;
                $this->index['neirong']='付费加入圈子后阅读';
                $tie = $this->index;
            }
        } else {
            //加入后
            if($cart){
                $this->index['jiaru'] = 1;
                $tie = $this->index;
            } else {
                $this->index['jiaru'] = 1;
                //$this->index['neirong']='加入圈子后阅读';
                $tie = $this->index;
            }
        }
        
        \Phpcmf\Service::V()->assign($tie);
        

        \Phpcmf\Service::V()->assign([
            'meta_title' => dr_lang('%s: %s', dr_comment_cname($this->module['comment']['cname']), $this->index['title']).SITE_SEOJOIN.dr_lang($this->module['name']),
            'meta_keywords' => $this->index['keywords'],
            'meta_description' => $this->index['description'],
        ]);
        \Phpcmf\Service::V()->assign([
            'quan' => $quantitle,
            'js' => $js,
			//'jss' => $jss,
            'fid' => $this->fid,
            'type' => $type,
            'page' => $page,
            'list' => $list,
            'code' => (int)$this->module['comment']['code'],
            'mingcheng' => $mingcheng,
            'yonghuzu' => $yonghuzu,
            'guishudi' => $guishudi,
            'touxiang' => dr_avatar($this->index['uid']),
            'index' => $tie,
            'catid' => (int)$this->index['catid'],
            'review' => $this->module['comment']['review'],
            'emotion' => dr_comment_emotion(),
            'myfield' => $myfield,
            'comment' => $comment,
            'commnets' => $total,
            'pagesize' => $pagesize,
            'post_url' => WEB_DIR.'index.php?s='.MOD_DIR.'&c='.$this->fid.'_comment&id='. $this->cid,
            'page_url' => WEB_DIR.'index.php?s='.MOD_DIR.'&c='.$this->fid.'_comment&m=index&id='. $this->cid,
            'is_reply' => (int)$this->module['comment']['reply'],
            'form_name' => $this->form['name'],
            'form_table' => $this->form['table'],
            'ajax_pages' => $this->_get_pages('javascript:'.$js.'('.$type.', {page})', $total, $pagesize),
        ]);

        if (empty($_GET['callback'])) {
            \Phpcmf\Service::V()->display($this->_get_tpl($this->fid, '_comment.html'));
        } else {
            ob_start();
            \Phpcmf\Service::V()->display($this->_get_tpl($this->fid, '_comment_ajax.html'));
            $html = ob_get_contents();
            ob_clean();
            $this->_jsonp(1, $html);
        }
    }
	
	// 评论列表2
	protected function _Index2() {
	
	    // 排序模式
	    $type = (int)str_replace('#', '', \Phpcmf\Service::L('input')->get('type'));
	    $order = '';
	    switch ($type) {
	        case 1:
	            $order = 'inputtime asc';
	            break;
	        case 2:
	            $order = 'support asc';
	            break;
	        case 3:
	            $order = 'avgsort desc';
	            break;
	        case 4:
	            $order = 'image desc';
	            break;
	        default:
	            $_GET['order'] && $order = strtolower(dr_get_order_string($_GET['order'], $order));
	            break;
	    }
	
	    // 判断排序字段是否可用
	
	    if (!dr_in_array(trim(str_replace([' asc', ' desc'], '', $order)), \Phpcmf\Service::L('cache')->get('table-'.SITE_ID, \Phpcmf\Service::M()->dbprefix($this->content_model->mytable.'_comment')))) {
	        if (isset($this->module['comment']['order']) && $this->module['comment']['order']) {
	            $order = $this->module['comment']['order'];
	        } else {
	            $order = 'inputtime desc';
	        }
	    }
	
	    // 获取评论数据
	    $comment = $this->comment_model->get_comment_index( $this->cid, $this->index['catid']);
	    if (!$comment) {
	        exit($this->_msg(0, dr_lang('内容【id#%s】索引数据读取失败',  $this->cid)));
	    }
	
	    $page = max(1, (int)\Phpcmf\Service::L('input')->get('page'));
	    $total = (int)\Phpcmf\Service::L('input')->get('total');
	
	    if (IS_API_HTTP) {
	        $pagesize = (int)$this->module['comment']['pagesize_api'];
	    } elseif (\Phpcmf\Service::IS_MOBILE()) {
	        $pagesize = (int)$this->module['comment']['pagesize_mobile'];
	    } else {
	        $pagesize = (int)$this->module['comment']['pagesize'];
	    }
	
	    !$pagesize && $pagesize = 10;
	
	    // 查询数据
	    list($list, $total) = $this->comment_model->get_comment_result($this->cid, $order, $page, $pagesize, $total, $this->module['comment']['field']);
	
	    // ajax动态无刷新调用
	    $js = 'dr_ajax_mform_'.$this->fid.'_comment_2_'. $this->cid;
	    $myfield = \Phpcmf\Service::L('Field')->toform(0, $this->module['comment']['field']);
	
	    \Phpcmf\Service::V()->assign($this->index);
	
	    \Phpcmf\Service::V()->assign([
	        'meta_title' => dr_lang('%s: %s', dr_comment_cname($this->module['comment']['cname']), $this->index['title']).SITE_SEOJOIN.dr_lang($this->module['name']),
	        'meta_keywords' => $this->index['keywords'],
	        'meta_description' => $this->index['description'],
	    ]);
	    \Phpcmf\Service::V()->assign([
	        'js' => $js,
			//'jss' => $jss,
	        'fid' => $this->fid,
	        'type' => $type,
	        'page' => $page,
	        'list' => $list,
	        'code' => (int)$this->module['comment']['code'],
	        'index' => $this->index,
	        'catid' => (int)$this->index['catid'],
	        'review' => $this->module['comment']['review'],
	        'emotion' => dr_comment_emotion(),
	        'myfield' => $myfield,
	        'comment' => $comment,
	        'commnets' => $total,
	        'pagesize' => $pagesize,
	        'post_url' => WEB_DIR.'index.php?s='.MOD_DIR.'&c='.$this->fid.'_comment&id='. $this->cid,
	        'page_url' => WEB_DIR.'index.php?s='.MOD_DIR.'&c='.$this->fid.'_comment&m=index2&id='. $this->cid,
	        'is_reply' => (int)$this->module['comment']['reply'],
	        'form_name' => $this->form['name'],
	        'form_table' => $this->form['table'],
	        'ajax_pages' => $this->_get_pages('javascript:'.$js.'('.$type.', {page})', $total, $pagesize),
	    ]);
	
	    if (empty($_GET['callback'])) {
	        \Phpcmf\Service::V()->display($this->_get_tpl($this->fid, '_comment.html'));
	    } else {
	        ob_start();
	        \Phpcmf\Service::V()->display($this->_get_tpl($this->fid, '_comment_ajax_2.html'));
	        $html = ob_get_contents();
	        ob_clean();
	        $this->_jsonp(1, $html);
	    }
	}
	// 评论列表3
	protected function _Index3() {
	
	    // 排序模式
	    $type = (int)str_replace('#', '', \Phpcmf\Service::L('input')->get('type'));
	    $order = '';
	    switch ($type) {
	        case 1:
	            $order = 'inputtime asc';
	            break;
	        case 2:
	            $order = 'support asc';
	            break;
	        case 3:
	            $order = 'avgsort desc';
	            break;
	        case 4:
	            $order = 'image desc';
	            break;
	        default:
	            $_GET['order'] && $order = strtolower(dr_get_order_string($_GET['order'], $order));
	            break;
	    }
	
	    // 判断排序字段是否可用
	
	    if (!dr_in_array(trim(str_replace([' asc', ' desc'], '', $order)), \Phpcmf\Service::L('cache')->get('table-'.SITE_ID, \Phpcmf\Service::M()->dbprefix($this->content_model->mytable.'_comment')))) {
	        if (isset($this->module['comment']['order']) && $this->module['comment']['order']) {
	            $order = $this->module['comment']['order'];
	        } else {
	            $order = 'inputtime desc';
	        }
	    }
	
	    // 获取评论数据
	    $comment = $this->comment_model->get_comment_index( $this->cid, $this->index['catid']);
	    if (!$comment) {
	        exit($this->_msg(0, dr_lang('内容【id#%s】索引数据读取失败',  $this->cid)));
	    }
	
	    $page = max(1, (int)\Phpcmf\Service::L('input')->get('page'));
	    $total = (int)\Phpcmf\Service::L('input')->get('total');
	
	    if (IS_API_HTTP) {
	        $pagesize = (int)$this->module['comment']['pagesize_api'];
	    } elseif (\Phpcmf\Service::IS_MOBILE()) {
	        $pagesize = (int)$this->module['comment']['pagesize_mobile'];
	    } else {
	        $pagesize = (int)$this->module['comment']['pagesize'];
	    }
	
	    !$pagesize && $pagesize = 10;
	
	    // 查询数据
	    list($list, $total) = $this->comment_model->get_comment_result($this->cid, $order, $page, $pagesize, $total, $this->module['comment']['field']);
	
	    // ajax动态无刷新调用
	    $js = 'dr_ajax_mform_'.$this->fid.'_comment_3_'. $this->cid;
		//$jss = 'dr_ajax_mform_'.$this->fid.'_comment_2_'. $this->cid;
	    $myfield = \Phpcmf\Service::L('Field')->toform(0, $this->module['comment']['field']);
	
	    \Phpcmf\Service::V()->assign($this->index);
	
	    \Phpcmf\Service::V()->assign([
	        'meta_title' => dr_lang('%s: %s', dr_comment_cname($this->module['comment']['cname']), $this->index['title']).SITE_SEOJOIN.dr_lang($this->module['name']),
	        'meta_keywords' => $this->index['keywords'],
	        'meta_description' => $this->index['description'],
	    ]);
	    \Phpcmf\Service::V()->assign([
	        'js' => $js,
			//'jss' => $jss,
	        'fid' => $this->fid,
	        'type' => $type,
	        'page' => $page,
	        'list' => $list,
	        'code' => (int)$this->module['comment']['code'],
	        'index' => $this->index,
	        'catid' => (int)$this->index['catid'],
	        'review' => $this->module['comment']['review'],
	        'emotion' => dr_comment_emotion(),
	        'myfield' => $myfield,
	        'comment' => $comment,
	        'commnets' => $total,
	        'pagesize' => $pagesize,
	        'post_url' => WEB_DIR.'index.php?s='.MOD_DIR.'&c='.$this->fid.'_comment&id='. $this->cid,
	        'page_url' => WEB_DIR.'index.php?s='.MOD_DIR.'&c='.$this->fid.'_comment&m=index3&id='. $this->cid,
	        'is_reply' => (int)$this->module['comment']['reply'],
	        'form_name' => $this->form['name'],
	        'form_table' => $this->form['table'],
	        'ajax_pages' => $this->_get_pages('javascript:'.$js.'('.$type.', {page})', $total, $pagesize),
	    ]);
	
	    if (empty($_GET['callback'])) {
	        \Phpcmf\Service::V()->display($this->_get_tpl($this->fid, '_comment.html'));
	    } else {
	        ob_start();
	        \Phpcmf\Service::V()->display($this->_get_tpl($this->fid, '_comment_ajax_3.html'));
	        $html = ob_get_contents();
	        ob_clean();
	        $this->_jsonp(1, $html);
	    }
	}
    // 模板自身文件识别
    protected function _get_tpl($fid, $tpl) {

        $path = \Phpcmf\Service::V()->get_dir();
        if (is_file($path.$fid.$tpl)) {
            return $fid.$tpl;
        }

        return 'mform'.$tpl;
    }


    public function _get_auth_value($name, $member) {

        if (!$this->module['comment'][$name]) {
            return 0;
        }

        if (!$member) {
            $auth = [0];
        } else {
            $auth = $member['groupid'];
            if (!$auth) {
                $auth = [0]; // 没有用户组的视为游客
            }
        }

        $value = [];
        foreach ($auth as $k) {
            if (isset($this->module['comment'][$name][$k])) {
                $value[] = (int)$this->module['comment'][$name][$k];
            }
        }

        return $value ? max($value) : 0;
    }

    // 评论或者回复
    protected function _Post() {

        if (!IS_POST) {
            $this->_json(0, dr_lang('非法请求'));
        }

        // 挂钩点 评论完成之后
        \Phpcmf\Hooks::trigger('mform_comment_before', $this->index);

        if ($this->module['comment']['my'] && $this->index['uid'] == $this->uid) {
            // 判断不能对自己评论
            $this->_json(0, dr_lang('系统禁止对自己提交'));
        } elseif ($this->index['is_comment'] == 1) {
            // 判断内容设置的评论权限
            $this->_json(0, dr_lang('该主题禁止提交'));
        } elseif ($this->module['comment']['buy']) {
            // 购买之后才能评论
            $this->_json(0, dr_lang('请到我的订单中操作'));
        } elseif ($this->module['comment']['num'] && \Phpcmf\Service::M()->db->table($this->comment_model->mytable.'_comment')->where('cid',  $this->cid)->where('uid', $this->uid)->countAllResults()) {
            // 只允许评论一次
            $this->_json(0, dr_lang('请勿重复提交'));
        }


        if (!$this->is_hcategory) {

            if (!$this->_get_auth_value('comment_add', $this->member)) {
                $this->_json(0, IS_DEV ? '需要在评论插件后台，开发发表评论权限' : dr_lang('无权限发表'));
            }
            $status = $this->_get_auth_value('comment_verify', $this->member) ? 0 : 1;

        } else {
            // 不走栏目权限，走自定义权限
            $rt = $this->content_model->_hcategory_member_comment_auth();
            if (!$rt['code']) {
                $this->_msg(0, $rt['msg'], $rt['data']);
            }
            // 评论状态
            $status = $this->content_model->_hcategory_member_comment_status();

        }

        $rid = (int)\Phpcmf\Service::L('input')->get('rid');
        if ($rid) {
            // 判断是否回复权限
            // 禁止回复
            if (!$this->module['comment']['reply']) {
                $this->_json(0, dr_lang('系统禁止回复功能'));
            }
            // 查询主题
            $row = $this->comment_model->table($this->comment_model->mytable.'_comment')->get($rid);
            if (!$row || $this->cid != $row['cid']) {
                $this->_json(0, dr_lang('您回复的主体不存在'));
            } elseif ($row['reply']) {
                $rid = $rid; // 如果他本是就是回帖内容
            } elseif ($this->module['comment']['reply'] == 2 && !(($this->member['uid'] == $row['uid'] && $row['uid'] == $this->index['uid']) || $this->member['is_admin'])) {
                // 判断仅自己
                $this->_json(0, dr_lang('您无权限回复'));
            }
        }

        // 判断会员权限
        //$this->member && $this->_member_option(1);

        // 验证操作间隔
        $name = 'mform-'.$this->fid.'-comment-post-'.md5(dr_now_url().$this->uid);
        if ($this->session()->get($name)) {
            $this->_json(0, dr_lang('您动作太快了'));
        }

        // 获取评论数据
        $comment = $this->comment_model->get_comment_index( $this->cid, $this->index['catid']);
        if (!$comment) {
            $this->_json(0, dr_lang('内容【id#%s】索引数据读取失败',  $this->cid));
        }

        // 判断评论内容
        //$content = $this->_safe_replace(\Phpcmf\Service::L('input')->post('content'));
        $content = \Phpcmf\Service::L('input')->post('content');
        if (!$content) {
            $this->_json(0, dr_lang('%s内容不能为空', dr_comment_cname($this->module['comment']['cname'])));
        }

        // 开启点评功能时，判断各项点评数，回复不做点评
        $review = [];
        if (!$rid && $this->module['comment']['review'] && $this->module['comment']['review']['option']) {
            foreach ($this->module['comment']['review']['option'] as $i => $name) {
                $review[$i] = (int)$_POST['review'][$i];
                if (!$review[$i]) {
                    $this->_json(0, dr_lang('选项[%s]未评分', $name));
                }
            }
        }

        // 自定义字段
        if (!$rid && isset($this->module['comment']['field']) && $this->module['comment']['field']) {
            \Phpcmf\Service::L('Field')->app(MOD_DIR);
            list($post, $return, $attach) = \Phpcmf\Service::L('Form')->validation(
                \Phpcmf\Service::L('input')->post('data'),
                [],
                $this->module['comment']['field']
            );
            // 输出错误
            if ($return) {
                $this->_json(0, $return['error']);
            }
            $my = $post[1];
        }

        // 提交评论
        $rt = $this->comment_model->insert_comment(
            [
                'index' => $this->index,
                'member' => $this->member,
                'reply_id' => $rid,
                'status' => $status,
            ],
            [
                'review' => $review,
                'content' => htmlspecialchars($content),
            ],
            $my
        );
        // 评论失败
        if (!$rt['code']) {
            $this->_json(0, $rt['msg']);
        }

        // 附件归档
        !$rid && SYS_ATTACHMENT_DB && $attach && \Phpcmf\Service::M('Attachment')->handle(
            $this->member['id'],
            \Phpcmf\Service::M()->dbprefix($this->comment_model->mytable.'_comment').'-'.$rt['code'],
            $attach
        );
        /**/
        if($rid){
            if($row['uid'] != $this->uid){
            $data = [
                 'catid'=> 10, //类型
                 'title' => '评论', //标题
                 'zhiding' => '', //置顶
                 'content'=> htmlspecialchars($content), //通知内容
                 'uid'=> $this->uid, //发布人的uid
                 'faxinren'=> $this->uid, //发布人的uid
                 'shouxinren'=> $row['uid'],//收信人
                 'tupian'=> '', //图片
                 'shipin'=> '', //视频
                 'yuyin'=> '', //语音
                 'fujian'=> '', //附件
                 'yidu'=> 0, //已读1,未读0
                 'quanziid'=> $this->index['cid'], //圈子ID
                 'quantieid'=> $this->index['id'], //圈帖ID
                 'url' => '',
            ];
            \Phpcmf\Service::M('auth')->addtongzhi($data);
            }
        } else {
            if($this->index['uid'] != $this->uid){
            $data = [
                 'catid'=> 10, //类型
                 'title' => '评论', //标题
                 'zhiding' => '', //置顶
                 'content'=> htmlspecialchars($content), //通知内容
                 'uid'=> $this->uid, //发布人的uid
                 'faxinren'=> $this->uid, //发布人的uid
                 'shouxinren'=> $this->index['uid'],//收信人
                 'tupian'=> '', //图片
                 'shipin'=> '', //视频
                 'yuyin'=> '', //语音
                 'fujian'=> '', //附件
                 'yidu'=> 0, //已读1,未读0
                 'quanziid'=> $this->index['cid'], //圈子ID
                 'quantieid'=> $this->index['id'], //圈帖ID
                 'url' => '',
            ];
            \Phpcmf\Service::M('auth')->addtongzhi($data);
            }
        }
        

        // 间隔30秒
        $this->session()->setTempdata($name, 1, 5);

        $status ? $this->_json(1, dr_lang('操作成功')) : $this->_json(1, dr_lang('操作成功，等待管理员审核'));
    }
	
	// 评论或者回复
	protected function _Postpingyu() {
	
	    if (!IS_POST) {
	        $this->_json(0, dr_lang('非法请求'));
	    }
		//$this->_json(0, dr_lang('非法请求'.$this->comment_model->mytable.'_pk'));
		//$table = $this->comment_model->mytable.'_pk';
		$pkfang = (int)\Phpcmf\Service::L('input')->get('pkfang');
		/*$pkshenhe = (int)\Phpcmf\Service::L('input')->get('pkshenhe');
		$pkjiangli = (int)\Phpcmf\Service::L('input')->get('pkjiangli');
		$xiaofeie = (int)\Phpcmf\Service::L('input')->get('xiaofeie');
		$jianglijifen = (int)\Phpcmf\Service::L('input')->get('jianglijifen');
		$jlrmb = (int)\Phpcmf\Service::L('input')->get('jlrmb');*/
	
	    // 挂钩点 评论完成之后
	    \Phpcmf\Hooks::trigger('mform_comment_before', $this->index);
	
	    if ($this->module['comment']['my'] && $this->index['uid'] == $this->uid) {
	        // 判断不能对自己评论
	        $this->_json(0, dr_lang('系统禁止对自己提交'));
	    } elseif ($this->index['is_comment'] == 1) {
	        // 判断内容设置的评论权限
	        $this->_json(0, dr_lang('该主题禁止提交'));
	    } elseif ($this->module['comment']['buy']) {
	        // 购买之后才能评论
	        $this->_json(0, dr_lang('请到我的订单中操作'));
	    } elseif ($this->module['comment']['num'] && \Phpcmf\Service::M()->db->table($this->comment_model->mytable.'_comment')->where('cid',  $this->cid)->where('uid', $this->uid)->countAllResults()) {
	        // 只允许评论一次
	        $this->_json(0, dr_lang('请勿重复提交'));
	    }
	
	
	    if (!$this->is_hcategory) {
	
	        if (!$this->_get_auth_value('comment_add', $this->member)) {
	            $this->_json(0, IS_DEV ? '需要在评论插件后台，开发发表评论权限' : dr_lang('无权限发表'));
	        }
	        $status = $this->_get_auth_value('comment_verify', $this->member) ? 0 : 1;
	
	    } else {
	        // 不走栏目权限，走自定义权限
	        $rt = $this->content_model->_hcategory_member_comment_auth();
	        if (!$rt['code']) {
	            $this->_msg(0, $rt['msg'], $rt['data']);
	        }
	        // 评论状态
	        $status = $this->content_model->_hcategory_member_comment_status();
	
	    }
		//dr_debug('status', $status);
		if ($this->index['pkshenhe'] ==0) {
			$status = 1;
		} else {
			$status = 0;
		}
		//$status = $this->index['pkshenhe'];
	
	    $rid = (int)\Phpcmf\Service::L('input')->get('rid');
	    if ($rid) {
	        // 判断是否回复权限
	        // 禁止回复
	        if (!$this->module['comment']['reply']) {
	            $this->_json(0, dr_lang('系统禁止回复功能'));
	        }
	        // 查询主题
	        $row = $this->comment_model->table($this->comment_model->mytable.'_comment')->get($rid);
	        if (!$row || $this->cid != $row['cid']) {
	            $this->_json(0, dr_lang('您回复的主体不存在'));
	        } elseif ($row['reply']) {
	            $rid = $rid; // 如果他本是就是回帖内容
	        } elseif ($this->module['comment']['reply'] == 2 && !(($this->member['uid'] == $row['uid'] && $row['uid'] == $this->index['uid']) || $this->member['is_admin'])) {
	            // 判断仅自己
	            $this->_json(0, dr_lang('您无权限回复'));
	        }
	    }
	
	    // 判断会员权限
	    //$this->member && $this->_member_option(1);
	
	    // 验证操作间隔
	    $name = 'mform-'.$this->fid.'-comment-post-'.md5(dr_now_url().$this->uid);
	    if ($this->session()->get($name)) {
	        $this->_json(0, dr_lang('您动作太快了'));
	    }
	
	    // 获取评论数据
	    $comment = $this->comment_model->get_comment_index( $this->cid, $this->index['catid']);
	    if (!$comment) {
	        $this->_json(0, dr_lang('内容【id#%s】索引数据读取失败',  $this->cid));
	    }
	
	    // 判断评论内容
	    $content = $this->_safe_replace(\Phpcmf\Service::L('input')->post('content'));
	    if (!$content) {
	        $this->_json(0, dr_lang('%s内容不能为空', dr_comment_cname($this->module['comment']['cname'])));
	    }
	
	    // 开启点评功能时，判断各项点评数，回复不做点评
	    $review = [];
	    if (!$rid && $this->module['comment']['review'] && $this->module['comment']['review']['option']) {
	        foreach ($this->module['comment']['review']['option'] as $i => $name) {
	            $review[$i] = (int)$_POST['review'][$i];
	            if (!$review[$i]) {
	                $this->_json(0, dr_lang('选项[%s]未评分', $name));
	            }
	        }
	    }
		
	
	    // 自定义字段
	    if (!$rid && isset($this->module['comment']['field']) && $this->module['comment']['field']) {
	        \Phpcmf\Service::L('Field')->app(MOD_DIR);
	        list($post, $return, $attach) = \Phpcmf\Service::L('Form')->validation(
	            \Phpcmf\Service::L('input')->post('data'),
	            [],
	            $this->module['comment']['field']
	        );
	        // 输出错误
	        if ($return) {
	            $this->_json(0, $return['error']);
	        }
	        $my = $post[1];
	    }
	
	    // 提交评论
	    $rt = $this->comment_model->insert_comment(
	        [
	            'index' => $this->index,
	            'member' => $this->member,
	            'reply_id' => $rid,
	            'status' => $status,
	        ],
	        [
	            'review' => $review,
	            'content' => htmlspecialchars($content),
	        ],
	        $my
	    );
		
	    // 评论失败
	    if (!$rt['code']) {
	        $this->_json(0, $rt['msg']);
	    }
	
	    // 附件归档
	    !$rid && SYS_ATTACHMENT_DB && $attach && \Phpcmf\Service::M('Attachment')->handle(
	        $this->member['id'],
	        \Phpcmf\Service::M()->dbprefix($this->comment_model->mytable.'_comment').'-'.$rt['code'],
	        $attach
	    );
	
	    // 间隔30秒
	    $this->session()->setTempdata($name, 1, 5);
		//评语开始
		$table = $this->comment_model->mytable.'_pk';
		//检测是否投过pk
		$pktouguo = \Phpcmf\Service::M()->db->table($table)->where('cid', $this->cid)->where('uid', $this->uid)->get()->getRowArray();
		if($pktouguo) {
			$this->_json(1, dr_lang('您已经PK过'));
		}
		$this->index['pkshenhe'];
		// 消费余额
		$xiaofeiesum = \Phpcmf\Service::M()->db->table($table)->where('cid', $this->cid)->selectSum('jianglirmb')->get()->getRowArray();
		// 消费积分
		$xiaofeiejifensum = \Phpcmf\Service::M()->db->table($table)->where('cid', $this->cid)->selectSum('jiangli')->get()->getRowArray();
		
		//人民币发值
		$pkrmbzhi = $this->index['xiaofeie'] - $xiaofeiesum['jianglirmb'];
		//积分值
		$pkjifenzhi = $this->index['xiaofeie'] - $xiaofeiejifensum['jiangli'];
		//蓝方
		if ($this->index['pkshenhe'] == 0) {
			$pkshenhe = $this->index['pkshenhe'];
			
			if($this->index['pkjiangli']==0){
				$jianglijifen = 0;
				$jlrmb = 0;
			} elseif ($this->index['pkjiangli']==1){
				if($this->index['jianglijifen'] <= $pkjifenzhi){
					$jianglijifen = $this->index['jianglijifen'];
					$jlrmb = 0;
				} else {
					$jianglijifen = 0;
					$jlrmb = 0;
				}
				
			} elseif ($this->index['pkjiangli']==2){
				if ($this->index['jlrmb'] <= $pkrmbzhi){
					$jianglijifen = 0;
					$jlrmb = $this->index['jlrmb'];
				} else {
					$jianglijifen = 0;
					$jlrmb = 0;
				}
				
			}
		} else {
			$pkshenhe = $this->index['pkshenhe'];
			if($this->index['pkjiangli']==0){
				$jianglijifen = 0;
				$jlrmb = 0;
			} elseif ($this->index['pkjiangli']==1){
				$jianglijifen = 0;
				$jlrmb = 0;
			} elseif ($this->index['pkjiangli']==2){
				$jianglijifen = 0;
				$jlrmb = 0;
			}
		}
		//添加数据
		\Phpcmf\Service::M()->db->table($table)->insert(array(
		    'cid' => $this->cid,
		    'uid' => $this->uid,
			'pkfang' => $pkfang,
			'pkshenhe' => $pkshenhe,
			'jiangli' => $jianglijifen,
			'jianglirmb' => $jlrmb,
		    'inputtime' => SYS_TIME
		));
		//更新统计
		//PK总数
		$pktongji = \Phpcmf\Service::M()->db->table($table)->where('cid', $this->cid)->countAllResults();
		//蓝方统计
		$lanfangtongji = \Phpcmf\Service::M()->db->table($table)->where('cid', $this->cid)->where('pkfang', 1)->countAllResults();
		//红方统计
		$hongfangtongji = \Phpcmf\Service::M()->db->table($table)->where('cid', $this->cid)->where('pkfang', 2)->countAllResults();
		//蓝方比例
		$pklanbili =($lanfangtongji / $pktongji)*100;
		//红方比例
		$pkhongbilis = 100 - $pklanbili;
		if ($pkhongbilis >= 80) {
			$pklanbili = 20;
			$pkhongbili = 80;
		} elseif($pklanbili >=80) {
			$pklanbili = 80;
			$pkhongbili = 20;
		} else {
			$pklanbili = ($lanfangtongji / $pktongji)*100;
			$pkhongbili = $pkhongbilis;
		}
		//更新统计
		$pkshuxing = [
			'lanfangtongji' => $lanfangtongji, //蓝方统计
			'lanfangbili' => $pklanbili, //蓝方比例
			'hongfangtongji' => $hongfangtongji, //红方统计
			'hongfangbili' => $pkhongbili, //红方比例
			'pktongji' => $pktongji, //pk总数
			];
		\Phpcmf\Service::M()->db->table($this->comment_model->mytable)->where('id', $this->cid)->update([
			'pk_shuxing' => dr_array2string($pkshuxing)
			]);
		//评语结束
		//网址
		$urls = '/index.php?s='.MOD_DIR.'&c=son&id='.$this->cid;
		//标题
		if($this->index['title']){
			$pktitle = $this->index['title'];
		} else {
			$pktitle = dr_strcut(dr_clearhtml($this->index['neirong']), 20);
		}
		//$this->index
		//dr_debug('index', $this->index);
		
		//不需要核对，直接增加积分
		if ($pkshenhe == 0){
			if($this->index['pkjiangli'] == 2) {
				
				if($xiaofeiesum['jianglirmb'] <= $pkrmbzhi) {
					if($jlrmb > 0){ //人民币大于0才执行添加
						\Phpcmf\Service::M('member')->add_money($this->uid, $jlrmb);
						//添加人民币记录
						\Phpcmf\Service::M('pay')->add_paylog([
							'uid' => $this->uid,
							'username' => '',
							'touid' => $this->index['uid'],
							'tousername' => '',
							'mid' => 'system',
							'title' => '《'.$pktitle.'》PK奖励',
							'value' => $jlrmb,
							'type' => finecms,
							'status' => 1,
							'result' => 'PK奖励',
							'paytime' => SYS_TIME,
							'inputtime' => SYS_TIME,
						]);
						//减去贴主费用
						\Phpcmf\Service::M('member')->add_money($this->index['uid'], -$jlrmb);
						//添加减去贴主人民币记录
						\Phpcmf\Service::M('pay')->add_paylog([
							'uid' => $this->index['uid'],
							'username' => '',
							'touid' => $this->uid,
							'tousername' => '',
							'mid' => 'system',
							'title' => '《'.$pktitle.'》PK奖励扣除费用',
							'value' => -$jlrmb,
							'type' => finecms,
							'status' => 1,
							'result' => 'PK奖励扣除',
							'paytime' => SYS_TIME,
							'inputtime' => SYS_TIME,
						]);
					}
				}
			} elseif ($this->index['pkjiangli'] ==1){
				if($xiaofeiejifensum['jiangli'] <= $pkjifenzhi) {
					if($jianglijifen > 0){ //积分大于0才执行添加
						\Phpcmf\Service::M('member')->add_score($this->uid, $jianglijifen, $note = 'PK奖励', $urls, $mark = '', $count = 0);
						\Phpcmf\Service::M('member')->add_score($this->index['uid'], -$jianglijifen, $note = 'PK扣除', $urls, $mark = '', $count = 0);
					}
				}
			}
			
			
		}
	
	    $status ? $this->_json(1, dr_lang('操作成功')) : $this->_json(1, dr_lang('操作成功，等待管理员审核'));
	}

    // 操作动作
    protected function _Op() {

        $op = \Phpcmf\Service::L('input')->get('t');
        $id = (int)\Phpcmf\Service::L('input')->get('rid');

        // 查询评论是否存在
        $data = $this->comment_model->table($this->comment_model->mytable.'_comment')->get($id);
        if (!$data) {
            $this->_json(0, dr_lang('主题不存在'));
        }

        // 获取评论索引数据
        $comment = $this->comment_model->get_comment_index( $this->cid, $this->index['catid']);
        if (!$comment) {
            $this->_msg(0, dr_lang('内容【id#%s】索引数据读取失败',  $this->cid));
        }

        // 验证操作间隔
        $name = 'mform-'.$this->fid.'-comment-op-'.md5(dr_now_url().$op.$id.$this->uid);
        if ($this->session()->get($name)) {
            $this->_json(0, dr_lang('您动作太快了'));
        }

        // 其他操作
        switch ($op) {
            case 'zc':
                $num = (int)$data['support'] + 1;
                $this->comment_model->table($this->comment_model->mytable.'_comment')->update($id, ['support' => $num]);
                $this->comment_model->table($this->comment_model->mytable.'_comment_index')->update($comment['id'], ['support' => (int)$comment['support'] + 1]);
                $this->session()->setTempdata($name, 1, 3600);
                $this->_json(1, $num);
                break;
            case 'fd':
                $num = (int)$data['oppose'] + 1;
                $this->comment_model->table($this->comment_model->mytable.'_comment')->update($id, ['oppose' => $num]);
                $this->comment_model->table($this->comment_model->mytable.'_comment_index')->update($comment['id'], ['oppose' => (int)$comment['oppose'] + 1]);
                $this->session()->setTempdata($name, 1, 3600);
                $this->_json(1, $num);
                break;

            case 'delete':
                if (!$this->uid) {
                    $this->_json(1, '无权限删除');
                } elseif ($this->uid == $data['uid']) {
                } elseif (!$this->member['adminid']) {
                    $this->_json(1, '当前用户['.$this->member['username'].']无权限删除');
                }
                // 删除
                \Phpcmf\Service::M()->table($this->comment_model->mytable.'_comment')->delete($data['id']);
                \Phpcmf\Service::M()->table($this->content_model->mytable.'_comment')->where('reply', $data['id'])->delete();
                \Phpcmf\Service::M('member')->delete_admin_notice(MOD_DIR.'/'.$this->fid.'_comment_verify/edit:cid/'.$data['cid'].'/id/'.$data['id'], SITE_ID);
                // 重新统计评论数
                $this->comment_model->comment_update_total($data);
                $this->comment_model->comment_update_review($data);
                $this->_json(1, '删除成功');
                break;

            default:
                $this->_json(1, '未定义的动作('.$op.')');
                break;
        }
    }

    // 格式化评论内容，方便二次开发和重写
    protected function _safe_replace($data) {
        return dr_safe_replace($data);
    }

    /**
     * 评论ajax分页 方便二次开发和重写
     */
    protected function _get_pages($url, $total, $pagesize) {

        $config = [];

        $file = 'page/'.(\Phpcmf\Service::IS_PC() ? 'pc' : 'mobile').'/ajax.php';
        if (is_file(WEBPATH.'config/'.$file)) {
            $config = require WEBPATH.'config/'.$file;
        } elseif (is_file(CONFIGPATH.$file)) {
            $config = require CONFIGPATH.$file;
        } else {
            $config['next_link'] = '>';
            $config['prev_link'] = '<';
            $config['last_link'] = '>|';
            $config['first_link'] = '|<';
            $config['cur_tag_open'] = '<a class="ds-current">';
            $config['cur_tag_close'] = '</a>';
        }

        $config['base_url'] = $url;
        $config['per_page'] = $pagesize;
        $config['total_rows'] = $total;
        $config['use_page_numbers'] = TRUE;
        $config['query_string_segment'] = 'page';

        return \Phpcmf\Service::L('Page')->initialize($config)->create_links();
    }


}
